pub use super::_entities::brands::{self, ActiveModel, Entity, Model};
pub(crate) use crate::models::_entities::brands::CreateBrandParams;
use loco_rs::prelude::*;
use serde::Deserialize;
use uuid::Uuid;


#[derive(Debug, Validate, Deserialize)]
pub struct Validator {
    #[validate(length(min = 1, message = "Name must not be empty."))]
    pub name: String,
}

impl Validatable for ActiveModel {
    fn validator(&self) -> Box<dyn Validate> {
        Box::new(Validator {
            name: self.name.as_ref().to_owned(),
        })
    }
}

#[async_trait::async_trait]
impl ActiveModelBehavior for ActiveModel {
    async fn before_save<C>(self, _db: &C, insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        self.validate()?;
        if insert {
            let mut this = self;
            this.id = Set(Uuid::new_v4().to_string());
            Ok(this)
        } else {
            Ok(self)
        }
    }
}

impl Model {
    /// finds a brand by the provided id
    ///
    /// # Errors
    ///
    /// When could not find brand or DB query error
    pub async fn find_by_id(db: &DatabaseConnection, id: &str) -> ModelResult<Self> {
        let brand = brands::Entity::find()
            .filter(model::query::condition().eq(brands::Column::Id, id).build())
            .one(db)
            .await?;
        brand.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// finds a brand by the provided slug
    ///
    /// # Errors
    ///
    /// When could not find brand or DB query error
    pub async fn find_by_slug(db: &DatabaseConnection, slug: &str) -> ModelResult<Self> {
        let brand = brands::Entity::find()
            .filter(
                model::query::condition()
                    .eq(brands::Column::Slug, slug)
                    .build(),
            )
            .one(db)
            .await?;
        brand.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// finds brands by the provided name
    ///
    /// # Errors
    ///
    /// When could not find brands or DB query error
    pub async fn find_by_name(db: &DatabaseConnection, name: &str) -> ModelResult<Vec<Self>> {
        let brands = brands::Entity::find()
            .filter(
                model::query::condition()
                    .eq(brands::Column::Name, name)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(brands)
    }

    /// Asynchronously creates a brand and saves it to the database.
    ///
    /// # Errors
    ///
    /// When could not save the brand into the DB
    pub async fn create(db: &DatabaseConnection, params: &CreateBrandParams) -> ModelResult<Self> {
        let txn = db.begin().await?;

        if let Some(slug) = &params.slug {
            if brands::Entity::find()
                .filter(
                    model::query::condition()
                        .eq(brands::Column::Slug, slug)
                        .build(),
                )
                .one(&txn)
                .await?
                .is_some()
            {
                return Err(ModelError::EntityAlreadyExists {});
            }
        }

        let brand = ActiveModel {
            name: ActiveValue::set(params.name.to_string()),
            slug: ActiveValue::set(params.slug.clone()),
            logo: ActiveValue::set(params.logo.clone().unwrap_or_default()),
            position: ActiveValue::set(params.position.unwrap_or_default()),
            active: ActiveValue::set(true),
            ..Default::default()
        }
        .insert(&txn)
        .await?;

        txn.commit().await?;

        Ok(brand)
    }
}

impl ActiveModel {
    /// Updates the brand's active status
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_active_status(
        mut self,
        db: &DatabaseConnection,
        active: bool,
    ) -> ModelResult<Model> {
        self.active = ActiveValue::set(active);
        Ok(self.update(db).await?)
    }

    /// Updates the brand's position
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_position(
         self,
        db: &DatabaseConnection,
        position: i32,
    ) -> ModelResult<Model> {
        let mut am: ActiveModel = self.into();
        am.position = ActiveValue::set(position);
        Ok(am.update(db).await?)
    }

    pub async fn update_name(
         self,
        db: &DatabaseConnection,
        name: String,
    ) -> ModelResult<Model> {
        let mut am: ActiveModel = self.into();

        am.name = ActiveValue::set(name);

        Ok(am.update(db).await?)
    }

    /// Updates the brand's logo
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_logo(
         self,
        db: &DatabaseConnection,
        logo: String,
    ) -> ModelResult<Model> {
        let mut am: ActiveModel = self.into();
        am.logo = ActiveValue::set(logo);
        Ok(am.update(db).await?)
    }
}
